import 'dart:convert';
import 'dart:ui';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_easyrefresh/material_footer.dart';
import 'package:flutter_easyrefresh/material_header.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:gzx_dropdown_menu/gzx_dropdown_menu.dart';
import 'package:flutter_yres/tool/constant.dart';
import 'package:flutter_yres/model/shop/hdk_list_model.dart';
import 'package:flutter_yres/tool/network/http_method.dart';
import 'package:flutter_yres/tool/network/http_url.dart';
import 'package:flutter_yres/model/shop/tbk_list_model.dart';
import 'package:flutter_yres/pages/shop/shop_detail_page.dart';
import 'package:cached_network_image/cached_network_image.dart';

class SearchGoodsListPage extends StatefulWidget {
  String search;
  SearchGoodsListPage({Key key, @required this.search}) : super(key: key);

  _SearchGoodsListPageState createState() => _SearchGoodsListPageState();
}

class _SearchGoodsListPageState extends State<SearchGoodsListPage> {
  List<TBKListModelData> homeListData = new List();
  String search = '';
  GZXDropdownMenuController _dropdownMenuController =
      GZXDropdownMenuController();
  List<String> sortList = ["价格", "销量", '佣金'];
  var _scaffoldKey = new GlobalKey<ScaffoldState>();
  GlobalKey _stackKey = GlobalKey();
  EasyRefreshController _controller = new EasyRefreshController();
  int page = 1;
  int currentShow = 0; //0 正常 1 网格
  String sort = 'total_sales_des';
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    search = widget.search;
    loadList();
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.instance = ScreenUtil(width: 750, height: 1334)..init(context);

    return Container(
      child: new Scaffold(
          appBar: PreferredSize(
            child: AppBar(
              brightness: Brightness.light,
              backgroundColor: white,
              elevation: 0,
            ),
            preferredSize: Size(0, 0),
          ),
          body: new Stack(
            key: _stackKey,
            children: <Widget>[
              new Column(
                children: <Widget>[
                  Container(
                    height: kToolbarHeight,
                    color: white,
                    alignment: Alignment.center,
                    child: new Row(
                      children: <Widget>[
                        Padding(
                          padding: EdgeInsets.all(0),
                          child: IconButton(
                            onPressed: () {
                              Navigator.of(context).pop();
                            },
                            icon: Icon(
                              Icons.arrow_back_ios,
                              color: black_99,
                            ),
                          ),
                        ),
                        Expanded(
                          flex: 1,
                          child: Container(
                            margin: EdgeInsets.fromLTRB(
                                ScreenUtil.getInstance().setHeight(DP_10),
                                0,
                                ScreenUtil.getInstance().setHeight(DP_10),
                                0),
                            height: ScreenUtil.getInstance().setHeight(DP_60),
                            decoration: BoxDecoration(
                                color: Color.fromARGB(255, 245, 245, 245),
                                borderRadius: BorderRadius.circular(20.0)),
                            child: ConstrainedBox(
                              constraints: BoxConstraints(maxHeight: DP_80),
                              child: TextField(
                                keyboardAppearance: Brightness.light,
                                maxLines: 1,
                                cursorColor: mainColor,
                                decoration: new InputDecoration(
                                    // contentPadding: EdgeInsets.all(0),
                                    prefixIcon: Icon(
                                      Icons.search,
                                      color: Colors.black45,
                                    ),
                                    hintText: "搜索商品、品牌",
                                    suffixIcon: ClipOval(
                                      child: Container(
                                        child: Icon(
                                          Icons.clear,
                                          color: Colors.white,
                                          size: ScreenUtil.getInstance()
                                              .setHeight(DP_30),
                                        ),
                                        margin: EdgeInsets.fromLTRB(
                                            80,
                                            ScreenUtil.getInstance()
                                                .setHeight(DP_15),
                                            ScreenUtil.getInstance()
                                                .setHeight(DP_15),
                                            ScreenUtil.getInstance()
                                                .setHeight(DP_15)),
                                        decoration: BoxDecoration(
                                            color: Colors.black45,
                                            borderRadius: BorderRadius.circular(
                                                ScreenUtil.getInstance()
                                                    .setHeight(DP_90))),
                                      ),
                                    ),
                                    border: InputBorder.none,
                                    hintStyle: TextStyle(
                                        color: Colors.black45,
                                        fontSize: ScreenUtil.getInstance()
                                            .setSp(NORMAL_FONT_SIZE))),
                              ),
                            ),
                          ),
                        ),
                        GestureDetector(
                          child: Container(
                              alignment: Alignment.center,
                              width: ScreenUtil.getInstance().setWidth(DP_120),
                              child: Text('确定',
                                  style: TextStyle(
                                      color: black_99,
                                      fontSize: ScreenUtil.getInstance()
                                          .setSp(NORMAL_FONT_SIZE)))),
                          onTap: () {
                            // Navigator.of(context)
                            //     .push(new MaterialPageRoute(builder: (context) {
                            //   return new GoodsListPage(
                            //     cat_id: "5",
                            //   );
                            // }));
                          },
                        )
                      ],
                    ),
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      Expanded(
                        flex: 2,
                        child: Container(
                          color: white,
                          padding: EdgeInsets.fromLTRB(0,
                              ScreenUtil.getInstance().setHeight(DP_8), 0, 0),
                          height: ScreenUtil.getInstance().setHeight(DP_60),
                          child: GZXDropDownHeader(
                            items: [
                              GZXDropDownHeaderItem(sortList[0]),
                              GZXDropDownHeaderItem(sortList[1]),
                              GZXDropDownHeaderItem(sortList[2]),
                            ],
                            stackKey: _stackKey,
                            controller: _dropdownMenuController,
                            onItemTap: (index) {},
                            height: ScreenUtil.getInstance().setHeight(DP_60),
                            color: white,
                            borderWidth: 1,
                            borderColor: white,
                            dividerColor: white,
                            style: TextStyle(
                                color: black_99,
                                fontSize: ScreenUtil.getInstance()
                                    .setSp(SMALL_FONT_SIZE)),
                            dropDownStyle: TextStyle(
                              fontSize: ScreenUtil.getInstance()
                                  .setSp(SMALL_FONT_SIZE),
                              color: mainColor,
                            ),
                            iconSize: ScreenUtil.getInstance().setHeight(DP_40),
                            iconColor: black_99,
                            iconDropDownColor: mainColor,
                          ),
                        ),
                      ),
                      Container(
                        height: ScreenUtil.getInstance().setHeight(DP_60),
                        color: white,
                        child: IconButton(
                          onPressed: () {
                            setState(() {
                              currentShow =
                                  (currentShow == 0 ? currentShow = 1 : 0);
                            });
                          },
                          icon: Image.asset(currentShow == 1
                              ? 'images/icon_list_vertical.png'
                              : 'images/icon_list_transverse.png'),
                        ),
                      ),
                    ],
                  ),
                  new Container(
                    height: MediaQuery.of(context).size.height -
                        kToolbarHeight -
                        ScreenUtil.getInstance().setHeight(DP_60) -
                        MediaQueryData.fromWindow(window).padding.top,
                    color: f0Color,
                    child: new EasyRefresh(
                      controller: _controller,
                      header: MaterialHeader(),
                      footer: MaterialFooter(),
                      enableControlFinishLoad: true,
                      enableControlFinishRefresh: true,
                      child: currentShow == 0
                          ? ListView.separated(
                              itemBuilder: _renderRow,
                              separatorBuilder:
                                  (BuildContext context, int index) {
                                return Container(
                                  color: divideColor,
                                  height: 1,
                                );
                              },
                              itemCount: homeListData == null
                                  ? 0
                                  : homeListData.length)
                          : GridView.builder(
                              shrinkWrap: true,
                              gridDelegate:
                                  SliverGridDelegateWithFixedCrossAxisCount(
                                      crossAxisCount: 2,
                                      mainAxisSpacing: 10.0,
                                      crossAxisSpacing: 10.0,
                                      childAspectRatio: 0.62),
                              itemBuilder: (context, index) {
                                return getItemContainer(context, index);
                              },
                              itemCount: homeListData == null
                                  ? 0
                                  : homeListData.length,
                            ),
                      onRefresh: () async {
                        page = 1;
                        loadList();
                      },
                      onLoad: () async {
                        page++;
                        loadList();
                      },
                    ),
                  ),
                ],
              ),
              GZXDropDownMenu(
                controller: _dropdownMenuController,
                animationMilliseconds: 0,
                menus: [
                  GZXDropdownMenuBuilder(
                      dropDownHeight:
                          ScreenUtil.getInstance().setHeight(DP_60) * 2 + 2,
                      dropDownWidget: new Column(
                        children: <Widget>[
                          Divider(
                            height: 1,
                            color: grey,
                          ),
                          new GestureDetector(
                            onTap: () {
                              setState(() {
                                sortList = ["价格", "销量", '佣金'];
                                sortList[0] = "价格升序";
                                _dropdownMenuController.hide();
                                sort = 'price_asc';
                                loadList();
                              });
                            },
                            child: Container(
                              width: double.infinity,
                              height: ScreenUtil.getInstance().setHeight(DP_60),
                              padding: EdgeInsets.all(10),
                              child: Text('价格升序'),
                            ),
                          ),
                          Divider(
                            height: 1,
                            color: grey,
                          ),
                          new GestureDetector(
                            onTap: () {
                              setState(() {
                                sortList = ["价格", "销量", '佣金'];
                                sortList[0] = "价格降序";
                                _dropdownMenuController.hide();
                                sort = 'price_des';
                                loadList();
                              });
                            },
                            child: Container(
                              width: double.infinity,
                              height: ScreenUtil.getInstance().setHeight(DP_60),
                              padding: EdgeInsets.all(10),
                              child: Text('价格降序'),
                            ),
                          ),
                        ],
                      )),
                  GZXDropdownMenuBuilder(
                      dropDownHeight:
                          ScreenUtil.getInstance().setHeight(DP_60) * 2 + 2,
                      dropDownWidget: new Column(
                        children: <Widget>[
                          Divider(
                            height: 1,
                            color: grey,
                          ),
                          new GestureDetector(
                            onTap: () {
                              setState(() {
                                sortList = ["价格", "销量", '佣金'];
                                sortList[1] = "销量升序";
                                _dropdownMenuController.hide();
                                sort = 'total_sales_asc';
                                loadList();
                              });
                            },
                            child: Container(
                              width: double.infinity,
                              height: ScreenUtil.getInstance().setHeight(DP_60),
                              padding: EdgeInsets.all(10),
                              child: Text('销量升序'),
                            ),
                          ),
                          Divider(
                            height: 1,
                            color: grey,
                          ),
                          new GestureDetector(
                            onTap: () {
                              setState(() {
                                sortList = ["价格", "销量", '佣金'];
                                sortList[1] = "销量降序";
                                _dropdownMenuController.hide();
                                sort = 'total_sales_des';
                                loadList();
                              });
                            },
                            child: Container(
                              width: double.infinity,
                              height: ScreenUtil.getInstance().setHeight(DP_60),
                              padding: EdgeInsets.all(10),
                              child: Text('销量降序'),
                            ),
                          ),
                        ],
                      )),
                  GZXDropdownMenuBuilder(
                      dropDownHeight:
                          ScreenUtil.getInstance().setHeight(DP_60) * 2 + 2,
                      dropDownWidget: new Column(
                        children: <Widget>[
                          Divider(
                            height: 1,
                            color: grey,
                          ),
                          new GestureDetector(
                            onTap: () {
                              setState(() {
                                sortList = ["价格", "销量", '佣金'];
                                sortList[2] = "佣金升序";
                                _dropdownMenuController.hide();
                                sort = 'tk_total_commi_asc';
                                loadList();
                              });
                            },
                            child: Container(
                              width: double.infinity,
                              height: ScreenUtil.getInstance().setHeight(DP_60),
                              padding: EdgeInsets.all(10),
                              child: Text('佣金升序'),
                            ),
                          ),
                          Divider(
                            height: 1,
                            color: grey,
                          ),
                          new GestureDetector(
                            onTap: () {
                              setState(() {
                                sortList = ["价格", "销量", '佣金'];
                                sortList[2] = "佣金降序";
                                _dropdownMenuController.hide();
                                sort = 'tk_total_commi_des';
                                loadList();
                              });
                            },
                            child: Container(
                              width: double.infinity,
                              height: ScreenUtil.getInstance().setHeight(DP_60),
                              padding: EdgeInsets.all(10),
                              child: Text('佣金降序'),
                            ),
                          ),
                        ],
                      )),
                ],
              ),
            ],
          )),
    );
  }

  loadList() async {
    FormData data = new FormData.fromMap(
        {'search': search, 'page_size': 10, 'page_no': page, 'sort': sort});
    Response<String> response =
        await HttpUtil().post(Api.GetTbkList_newUrl, data: data);
    Map userMap = json.decode(response.data);
    TBKListModelEntity itemEntity = new TBKListModelEntity.fromJson(userMap);
    print(userMap);
    if (itemEntity.code == 1) {
      if (mounted) {
        setState(() {
          if (page == 1) {
            homeListData.clear();
            homeListData = itemEntity.data;
            _controller.finishRefresh();
          } else {
            homeListData.addAll(itemEntity.data);
            _controller.finishLoad();
          }
        });
      }
    }
  }

  Widget _renderRow(BuildContext context, int index) {
    var price = RichText(
      textAlign: TextAlign.left,
      text: TextSpan(style: TextStyle(color: Colors.red), children: [
        TextSpan(text: '¥', style: TextStyle(fontSize: 12.0)),
        TextSpan(
            text: homeListData[index].zk_final_price,
            style: TextStyle(fontSize: 18.0)),
        TextSpan(
          text: homeListData[index].reserve_price,
          style: TextStyle(
              fontSize: 12.0,
              color: Colors.grey,
              decoration: TextDecoration.lineThrough,
              decorationColor: Colors.grey),
        ),
      ]),
      maxLines: 1,
      overflow: TextOverflow.ellipsis,
    );
    var quanHeader = Container(
      width: ScreenUtil.getInstance().setWidth(40),
      height: ScreenUtil.getInstance().setWidth(34),
      decoration: BoxDecoration(
        image: DecorationImage(
          image: AssetImage("images/item_youhuiquan_header.png"),
          fit: BoxFit.cover,
        ),
      ),
    );
    var quan = Container(
      width: ScreenUtil.getInstance().setWidth(70),
      height: ScreenUtil.getInstance().setWidth(34),
      decoration: BoxDecoration(
        image: DecorationImage(
          image: AssetImage("images/item_youhuiquan_footer.png"),
          fit: BoxFit.cover,
        ),
      ),
      child: Center(
          child: Text(
        homeListData[index].coupon_amount == null
            ? '0元'
            : homeListData[index].coupon_amount + '元',
        style: TextStyle(color: Colors.white, fontSize: 10),
      )),
    );
    var yongjin = Container(
      margin: EdgeInsets.fromLTRB(ScreenUtil.getInstance().setWidth(20), 0, ScreenUtil.getInstance().setWidth(20), 0),
      height: ScreenUtil.getInstance().setWidth(34),
      color: Color.fromRGBO(250, 226, 226, 1),
      child: Center(
          child: Text('预估赚¥' + homeListData[index].commission,
              style: TextStyle(color: Colors.red, fontSize: 10))),
    );
    return new GestureDetector(
      onTap: () {
        HDKListModelData model = new HDKListModelData();
        TBKListModelData data = homeListData[index];
        model.itemid = data.num_iid;
        Navigator.push(
            context,
            MaterialPageRoute(
                //导航打开新视图
                builder: (context) =>
                    ShopDetailPage(hdkmodel: model) //打开第二个页面，并传值，传递值的名称是model
                ));
      },
      child: Container(
        padding: EdgeInsets.all(10),
        color: white,
        child: new Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            homeListData[index].pict_url == ""
                ? Image.asset('images/pic_default.png',
                    width: ScreenUtil.getInstance().setWidth(180),
                    fit: BoxFit.fill,
                    height: ScreenUtil.getInstance().setWidth(180))
                : CachedNetworkImage(
                    width: ScreenUtil.getInstance().setHeight(180),
                    height: ScreenUtil.getInstance().setHeight(180),
                    fit: BoxFit.fill,
                    imageUrl: homeListData[index].pict_url,
                    placeholder: (context, url) => Image.asset(
                      'images/pic_default.png',
                      width: ScreenUtil.getInstance().setHeight(180),
                      height: ScreenUtil.getInstance().setHeight(180),
                      fit: BoxFit.fill,
                    ),
                    errorWidget: (context, url, error) => Image.asset(
                      'images/pic_default.png',
                      width: ScreenUtil.getInstance().setHeight(180),
                      height: ScreenUtil.getInstance().setHeight(180),
                      fit: BoxFit.fill,
                    ),
                  ),
            Expanded(
              flex: 1,
              child: Container(
                padding: EdgeInsets.fromLTRB(10, 5, 5, 5),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Text(
                      homeListData[index].title,
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(
                          fontSize: ScreenUtil.getInstance().setSp(28),
                          color: black,
                          fontWeight: FontWeight.w400),
                    ),
                    Row(
                      children: <Widget>[
                        Expanded(
                          flex: 1,
                          child: price,
                        ),
                        Container(
                          margin: EdgeInsets.all(ScreenUtil.getInstance().setWidth(5)),
                          child: Text('已售' + homeListData[index].volume,
                              style: TextStyle(
                                  fontSize: 12.0, color: Colors.grey)),
                        ),
                      ],
                    ),

                    Container(
                      margin: EdgeInsets.all(ScreenUtil.getInstance().setWidth(5)),
                      child: Row(
                        children: <Widget>[
                          Expanded(
                            flex: 1,
                            child: Row(
                              children: <Widget>[quanHeader, quan],
                            ),
                          ),
                          Expanded(flex: 2, child: yongjin)
                        ],
                      ),
                    ),
                    // Padding(
                    //   padding: EdgeInsets.fromLTRB(0, 3, 5, 0),
                    //   child: Text(
                    //     homeListData[index].coupon_amount,
                    //     style: TextStyle(
                    //       fontSize: ScreenUtil.getInstance().setSp(26),
                    //       color: black_99,
                    //     ),
                    //   ),
                    // ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

//商品cell
  getItemContainer(BuildContext context, int index) {
    TBKListModelData model = homeListData[index];
    var price = RichText(
      textAlign: TextAlign.left,
      text: TextSpan(style: TextStyle(color: Colors.red), children: [
        TextSpan(text: '¥', style: TextStyle(fontSize: 12.0)),
        TextSpan(text: model.zk_final_price, style: TextStyle(fontSize: 18.0)),
        TextSpan(
          text: model.reserve_price,
          style: TextStyle(
              fontSize: 12.0,
              color: Colors.grey,
              decoration: TextDecoration.lineThrough,
              decorationColor: Colors.grey),
        ),
      ]),
      maxLines: 1,
      overflow: TextOverflow.ellipsis,
    );
    var quanHeader = Container(
      width: ScreenUtil.getInstance().setWidth(40),
      height: ScreenUtil.getInstance().setWidth(34),
      decoration: BoxDecoration(
        image: DecorationImage(
          image: AssetImage("images/item_youhuiquan_header.png"),
          fit: BoxFit.cover,
        ),
      ),
    );
    var quan = Container(
      width: ScreenUtil.getInstance().setWidth(70),
      height: ScreenUtil.getInstance().setWidth(34),
      decoration: BoxDecoration(
        image: DecorationImage(
          image: AssetImage("images/item_youhuiquan_footer.png"),
          fit: BoxFit.cover,
        ),
      ),
      child: Center(
          child: Text(
        model.coupon_amount==null?'0元' :model.coupon_amount+'元',
        style: TextStyle(color: Colors.white, fontSize: 10),
      )),
    );
    var yongjin = Container(
      margin: EdgeInsets.fromLTRB(ScreenUtil.getInstance().setWidth(20), 0, ScreenUtil.getInstance().setWidth(20), 0),
      height: ScreenUtil.getInstance().setWidth(34),
      color: Color.fromRGBO(250, 226, 226, 1),
      child: Center(
          child: Text('预估赚¥' + model.commission,
              style: TextStyle(color: Colors.red, fontSize: 10))),
    );
    return GestureDetector(
      child: Container(
          color: Colors.white,
          margin: EdgeInsets.fromLTRB(ScreenUtil.getInstance().setWidth(10), 0, ScreenUtil.getInstance().setWidth(10), 0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              CachedNetworkImage(
                width: (ScreenUtil.getInstance().setWidth(750) - ScreenUtil.getInstance().setWidth(20)) / 2,
                height: (ScreenUtil.getInstance().setWidth(750) - ScreenUtil.getInstance().setWidth(20)) / 2,
                fit: BoxFit.fill,
                imageUrl: model.pict_url,
                placeholder: (context, url) => Image.asset(
                  'images/pic_default.png',
                  width: (ScreenUtil.getInstance().setWidth(750) - ScreenUtil.getInstance().setWidth(20)) / 2,
                  height: (ScreenUtil.getInstance().setWidth(750) - ScreenUtil.getInstance().setWidth(20)) / 2,
                  fit: BoxFit.fill,
                ),
                errorWidget: (context, url, error) => Image.asset(
                  'images/pic_default.png',
                  width: (ScreenUtil.getInstance().setWidth(750) - ScreenUtil.getInstance().setWidth(20)) / 2,
                  height: (ScreenUtil.getInstance().setWidth(750) - ScreenUtil.getInstance().setWidth(20)) / 2,
                  fit: BoxFit.fill,
                ),
              ),
              Text(model.title, maxLines: 2),
              Container(
                margin: EdgeInsets.all(ScreenUtil.getInstance().setWidth(5)),
                child: price,
              ),
              Container(
                margin: EdgeInsets.all(ScreenUtil.getInstance().setWidth(5)),
                child: Text('已售' + model.volume,
                    style: TextStyle(fontSize: 12.0, color: Colors.grey)),
              ),
              Container(
                margin: EdgeInsets.all(ScreenUtil.getInstance().setWidth(5)),
                child: Row(
                  children: <Widget>[
                    Expanded(
                      flex: 1,
                      child: Row(
                        children: <Widget>[quanHeader, quan],
                      ),
                    ),
                    Expanded(flex: 2, child: yongjin)
                  ],
                ),
              )
            ],
          )),
      onTap: () {
        HDKListModelData model = new HDKListModelData();
        TBKListModelData data = homeListData[index];
        model.itemid = data.num_iid;
        Navigator.push(
            context,
            MaterialPageRoute(
                //导航打开新视图
                builder: (context) =>
                    ShopDetailPage(hdkmodel: model) //打开第二个页面，并传值，传递值的名称是model
                ));
      },
    );
  }
}
